#!/bin/bash

set -e

BACKUP_FILE=$1

if [ -z "$BACKUP_FILE" ]; then
    echo "❌ Usage: $0 <backup-file>"
    echo "📊 Available backups:"
    ls -la ./backups/*.tar.gz 2>/dev/null || echo "No backups found"
    exit 1
fi

if [ ! -f "$BACKUP_FILE" ]; then
    echo "❌ Backup file not found: $BACKUP_FILE"
    exit 1
fi

echo "🔄 Restoring from backup: $BACKUP_FILE"

# Stop services
echo "🛑 Stopping services..."
docker-compose -f docker-compose.prod.yml down || true

# Create backup of current state
if [ -d "./data" ]; then
    CURRENT_BACKUP="./backups/pre-restore-$(date +%Y%m%d-%H%M%S)"
    echo "💾 Backing up current state to: $CURRENT_BACKUP"
    cp -r ./data "$CURRENT_BACKUP"
fi

# Extract backup
echo "📦 Extracting backup..."
tar -xzf "$BACKUP_FILE"

echo "✅ Restore completed!"
echo "🚀 You can now start the services with: docker-compose -f docker-compose.prod.yml up -d"
